package com.pzhu.security.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;

@Component
public class JwtTokenService implements TokenService {
    private static TokenConfig tokenConfig;

    @Autowired
    public void TokenService(TokenConfig tokenConfig) {
        this.tokenConfig = tokenConfig;
    }

    @Override
    public String generate(TokenClaim... claims) {

        JWTCreator.Builder token = JWT.create()
                .withAudience(tokenConfig.audience)
                .withIssuer(tokenConfig.issuer)
                .withExpiresAt(new Date(System.currentTimeMillis() + tokenConfig.expiresIn * 1000 * 60));
        Arrays.asList(claims).forEach(claim -> token.withClaim(claim.getName(), claim.getValue()));

        return token.sign(Algorithm.HMAC256(tokenConfig.secret));
    }

    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(tokenConfig.secret)).build().verify(token);
    }

    public static Claim getClaim(HttpServletRequest request, String name) {
        String token = request.getHeader("token");
        DecodedJWT verify = JwtTokenService.verify(token);
        Claim claim = verify.getClaim(name);
        return claim;
    }
}
